<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>书签</title>
  <style>
    .tip {
      background: #959595;
      color: wheat;
      padding: 5px;
      margin: 0;
      margin-bottom: 2px;
      word-break: break-all;
    }

    .folder {
      background: #e5e3ca;
      display: flex;
      padding: 4px 8px;
      align-items: center;
      color: black;
      font-size: 16px;
      border-bottom: 1px solid #f3f2f1;
      position: relative;
    }

    .link {
      /* background: #91d8d3; */
      display: flex;
      padding: 4px 8px;
      align-items: center;
      color: black;
      font-size: 17px;
      border-bottom: 1px solid #bebebe;
      position: relative;
    }

    .zz {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
    }

    .img {
      max-width: 26px;
      margin-right: 10px;
      width: 26px;
      height: 26px;
    }
  </style>
</head>

<body style="background: #e9e9e9; margin: 0; padding: 0; position: relative;">
  <div id="tip" class="tip"></div>

  <div id="folderDir" onclick="obj.folderFn(event)">
    <!-- <div class="folder">
      <img class="img" src="../images/folder.svg">
      <div>视频1</div>
    </div> -->
  </div>

  <div id="linkDir" style="margin-bottom: 70px;" onclick="obj.openLink(event)">
    <!-- <div class="link">
      <img class="img" src="../images/链接.png">
      <div>视频3</div>
      <div class="zz"></div>
    </div> -->
  </div>
  <div onclick="obj.back()"
    style="position: fixed; bottom: 0; display: flex; justify-content: center; align-items: center; width: 100%; height: 70px; background: #096722; color: wheat;">
    返回</div>
</body>
<script>
  let tipArr = [];
  let obj = {
    getlist(path = 'bookmarks/', ref = 'master') {
      let than = this;
      /* 初始化 -  获取仓库中的所有文件 */
      fetch('/getlist', {
        method: 'GET',
      }).then(res => res.json())
        .catch((error) => {
          // console.log('获取仓库路径 ', error)
        }).then((resp) => {
          // console.log('getlist', resp)
          than.addFiles(resp);
          window.files = resp
          db.setData('files', resp)
        })
    },
    addFiles(arr) {
      /* 初始化 - 显示仓库中的所有文件 */
      this.clear()
      arr.forEach(element => {
        var div = document.createElement("div");
        div.setAttribute('class', 'folder')
        div.setAttribute('data-name', element.name);
        div.setAttribute('data-path', element.path);
        div.innerHTML = ` <img class="img" src="../images/folder.svg"/> 
            <div >${element.name}</div>
            <div class="zz" data-name="${element.name}" data-path="${element.path}"></div>`
        document.getElementById("folderDir").appendChild(div)
      });
    },
    clear() {
      /* 删除现有的选项 */
      document.getElementById('folderDir').innerHTML = ''
      document.getElementById('linkDir').innerHTML = ''
    },
    folderFn(event) {
      /* 点击文件夹事件 */
      let { target } = event
      let than = this;
      if (target.getAttribute('data-title')) {
        let id = target.getAttribute('data-id')
        // console.log(`title`, target.getAttribute('data-title'))
        window.bookmarks.cur.forEach((item, index) => {
          // console.log(``, Number(id), Number(item.id))
          if (Number(id) == Number(item.id)) {
            window.bookmarks = {
              father: window.bookmarks,
              cur: item.children,
              son: null
            }
            than.addBookmarks(item.children)
            than.changeTip(target.getAttribute('data-title'))
          }
        })
      } else {
        // console.log(``, target.getAttribute('data-name'))
        // console.log(``, target.getAttribute('data-path'))
        this.getFileContent(target.getAttribute('data-path'))
        // document.getElementById('tip').innerHTML = target.getAttribute('data-name')
        than.changeTip(target.getAttribute('data-name'))
      }
    },
    back() {
      /* 返回上一步 */
      let than = this;
      if (window.bookmarks.father) {
        than.addBookmarks(window.bookmarks.father.cur)
        window.bookmarks = {
          father: window.bookmarks.father.father,
          cur: window.bookmarks.father.cur,
          son: null
        }
      } else {
        than.addFiles(window.files)
      }
      than.changeTip()
    },
    openLink(event) {
      /* 打开链接 */
      let { target } = event
      let url = target.getAttribute('data-url')
      window.open(url)
    },
    getFileContent(path) {
      /* 获取文件Blob */
      let than = this
      // console.log(`path`, path)
      fetch("/getFileContent?path=" + path, {
        method: 'GET',
      }).then(res => res.json())
        .catch((error) => {
          // console.log('获取文件Blob ', error)
        })
        .then((resp) => {
          try {
            // console.log(`info`, resp)
            than.addBookmarks(resp)
            window.bookmarks = {
              father: null,
              cur: resp,
              son: null
            }
            // db.setData('bookmarks', resp)
          } catch (e) {
            // console.log('error', e)
            alert("请求书签数据出差")
          }
        })
    },
    addBookmarks(arr) {
      /* 初始化 - 显示仓库中的所有文件 */
      if (arr.length == 0) { alert("没有书签"); return; }
      this.clear()
      arr.forEach((element, index) => {
        // console.log(``, element, index)
        // console.log(element.id)
        if (element.children) {
          // console.log(element)
          var div = document.createElement("div");
          div.setAttribute('class', 'folder')
          div.innerHTML = ` <img class="img" src="../images/folder.svg"/> 
            <div >${element.title}</div>
            <div class="zz" data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}"></div>`
          document.getElementById("folderDir").appendChild(div)
        } else {
          let urlArr = element.url.split('/')
          let favicon = urlArr[0] + '//' + urlArr[2] + '/favicon.ico'
          var div = document.createElement("div");
          div.setAttribute('class', 'link')
          div.innerHTML = ` <img class="img" src="${favicon}" /> 
            <div >${element.title}</div>
            <div class="zz" data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}"></div>`
          document.getElementById("linkDir").appendChild(div)
        }
      });
    },
    changeTip(text) {
      if (text) {
        tipArr.push(text)
      } else {
        tipArr.pop()
      }
      document.getElementById('tip').innerHTML = tipArr.join('/')
    },
  }

  obj.getlist()


  class Local {
    constructor(key) {
      this.key = key;
      this.initLo();
    }
    setData(key, value) { // 保存键值对到本地
      if (typeof value === 'undefined') {
        return localStorage.setItem(this.key, JSON.stringify(key));
      }
      if (typeof value === 'string') {
        return localStorage.setItem(key, value);
      }
      try {
        localStorage.setItem(key, JSON.stringify(value));
      } catch (err) {
        return err;
      }
    }
    getData(key) { // 获取指定key的数据
      const value = localStorage.getItem(key || this.key);
      try {
        return JSON.parse(value);
      } catch (err) {
        return value;
      }
    }
    removeData(key) { // 删除指定key的数据
      return localStorage.removeItem(key);
    }
    clearData() { // 删除所有的本地数据
      return localStorage.clear();
    }
    initLo() { // 初始化
      if (!window.localStorage) {
        throw new Error("浏览器不支持 localstorage 本地存储！！！")
      }
    }
  }

  (function local(local = 'local') {
    var local_ = local;
    if (window[local]) return console.log('属性名重复！！');
    try {
      window[local_] = new Local(local);
      console.log('封装本地存储成功，可以直接使用 ' + local_ + ' 对象来操作本地存储数据！')
    } catch (err) {
      console.log(err)
      return err;
    }
  })("db")	// 自定义缓存名

</script>

</html>